package officialaccount

import (
	. "Go-Easy/pkg/config"
	. "Go-Easy/pkg/http"
	. "Go-Easy/pkg/wechat"
	"encoding/json"
	"net/url"
	"strings"
)

func GetToken() (WechartRespond, error) {
	par := url.Values{}
	par.Set("grant_type", Wechat.WechartOfficialAccount.Grant_Type)
	par.Set("appid", Wechat.WechartOfficialAccount.AppID)
	par.Set("secret", Wechat.WechartOfficialAccount.Secret)

	var wechartres WechartRespond
	r, l, err := HttpGet(Wechat.WechartOfficialAccount.GetTokenURL,par)
	if err != nil {
		return wechartres, err
	}
	//切片中会有很多00填充，如果不做读取位数限制，则会报错:invalid character '\x00' after top-level value
	if err = json.Unmarshal([]byte(r)[:l], &wechartres); err == nil {
		return wechartres, nil
	} else {
		return wechartres, err
	}
}

func SendMessage(WechartToken string, Messages Message) (WechartRespond, error) {
	Message := strings.Replace(Wechat.WechartOfficialAccount.MessageTemplate, "$openid$", Messages.Recipient, -1)
	Message = strings.Replace(Message, "$template$", Wechat.WechartOfficialAccount.TemplateID, -1)
	Message = strings.Replace(Message, "$meaages$", Messages.Message, -1)

	var URL = Wechat.WechartOfficialAccount.SendMessageURL + "?access_token=" + WechartToken
	var wechartres WechartRespond
	if r, l, err := HttpPost_raw(URL, strings.NewReader(Message)); err == nil {
		if err = json.Unmarshal([]byte(r)[:l], &wechartres); err == nil {
			return wechartres, nil
		} else {
			return wechartres, err
		}
	} else {
		return wechartres, err
	}
}
